//
//  spriteDescription.m
//  cliptest
//
//  Created by James Tong on 31/05/2010.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "LDSpriteLayer.h"

@implementation LDSpriteLayer

- (id) init {
	if (self = [super init]) {
		spriteArray = [[NSMutableArray alloc] init];

	}
	
	return self;
}

// 讀取sprite description file，建立sprite並逐一加入layer
// fname是description file的filename
// textureArray是包含了多張spriteSheet的NSMutableArray
- (void) loadSpriteWithDescriptionFile : (NSString *)fname : (NSMutableArray *) textureArray {
	
	int cmd;
	id tex;
	// spriteArray就是整個sprite layer！
	// 用NSMutableArray就可建立一個可自動expand的array
	// spriteArray = [[NSMutableArray alloc] init];
	
	// 取得完整的bundle path
	NSString * path = [[NSBundle mainBundle] pathForResource: fname ofType: @"def"];

 	fp = fopen([path cStringUsingEncoding:1],"r");
	if (fp == NULL) {
		NSLog(@"fail");		// 應該要更有更好的error handling
		return;
	}
	
	while (1) {
		// 讀入一行
		if (fgets(buf, 512, fp)==NULL) {
			break;
		}
		
		// 將這一行資料，交給parseDescription這個method分析
		cmd = [self parseDescription : buf];
		
		if (cmd == BEGIN) {								// 如果是begin command便加一個新sprite
			sprite01 = [LDSprite new];
		}
		else if (cmd == END) {							// 如果是end command便設定好一切再加入spriteArray中
			// 下面兩行code的次序非常重要，否則便會出錯
			tex = [textureArray objectAtIndex:textureIndex];	// 從textureArray(儲存著多張texture的array)中對應的spritesheet
			[sprite01 linkSpritesheet:tex];				// 告訴應該用那張spritesheet
			
			// 設定各個variables
			// strcpy(sprite01.key, key, 15);
			
			//sprite01.key = [NSString stringWithCString:key encoding: NSUTF8StringEncoding];
			//sprite01.key = @"success.png";
			[sprite01 setSpriteKey : key];
			sprite01.tileWidth		= tileWidth;
			sprite01.tileHeight		= tileHeight;
			sprite01.tileInterval	= tileInterval;
			sprite01.tileTimer		= tileTimer;
			sprite01.startTile		= startTile;
			sprite01.endTile		= endTile;
			sprite01.nowTile		= nowTile;
			[sprite01 setTile:nowTile]; 
			sprite01.tileRepeat		= tileRepeat;
			sprite01.movesInterval	= movesInterval;
			sprite01.movesTimer		= movesTimer;
			sprite01.startX			= sprite01.nowX		// 留意將nowX在這裡會自動設定好
									= startX;
			sprite01.startY			= sprite01.nowY		// 留意將nowY在這裡會自動設定好
									= startY;
			sprite01.endX			= endX;
			sprite01.endY			= endY;
			sprite01.extendXY		= extendXY;
			if (sprite01.extendXY == YES)
				[sprite01 extendEndXY];
			sprite01.movesIncX		= movesIncX;
			sprite01.movesIncY		= movesIncY;
			sprite01.movesRepeat	= movesRepeat;
			sprite01.drawMe			= drawMe;
			
			// 如果在程式中更改了sprite中的startX, startY, endX, endY, movesIncX或movesIncY
			// 就必須要執行一次calDistantRatio這個method，否則sprite在斜線移動時便不會依正確路線
			[sprite01 calcDistantRatio];
			
			[spriteArray addObject:sprite01];			// 最後將sprite加到layer
			//[sprite01 release];
		}
//		else if (cmd == COMMENT) {
//			NSLog(@"Comments");
//		}
		else if (cmd == UNKNOWN) {
			NSLog(@"<Unknown>");
		}
		
	} // while

	fclose(fp);

}

// 這個method會分析description file中的句子
// 並將分析出的數據放入臨時的variables中
// 最後return句子是那一種命令
- (int) parseDescription : (char *)s {

	int randomNumber1, randomNumber2;
	
	char *tmp = strtok(s, ", \t\n");

	// 在每一個if, else if中，會先抽取command，然後按command再抽取餘下的數據
	// #號是comment，#號以後所有資料都會忽略
	if (tmp == NULL) {
		return UNKNOWN;
	}
	
	if (!strcmp("beginsprite",tmp)) {
		return BEGIN;
	}
	else if (!strcmp("endsprite",tmp)) {
		return END;
	}
	else if (!strcmp("spritename",tmp)) {
		tmp = strtok(NULL, ", \t\n"); 
		strcpy(key, tmp);
		//key[15] = '\0';
		return OTHER;
	}
	else if (!strcmp("textureIndex",tmp)) {
		tmp = strtok(NULL, ", \t\n");
		textureIndex = atoi(tmp);
		return OTHER;
	}
	else if (!strcmp("tilesize",tmp)) {
		tmp = strtok(NULL, ", \t\n");
		tileWidth = atof(tmp);
		tmp = strtok(NULL, ", \t\n");
		tileHeight = atof(tmp);
		return OTHER;
	}
	else if (!strcmp("tiletime",tmp)) {
		tmp = strtok(NULL, ", \t\n");
		tileInterval = atoi(tmp);
		tmp = strtok(NULL, ", \t\n");
		tileTimer = atoi(tmp);
		return OTHER;
	}
	else if (!strcmp("tilerange",tmp)) {
		tmp = strtok(NULL, ", \t\n");
		startTile = atoi(tmp);
		tmp = strtok(NULL, ", \t\n");
		endTile = atoi(tmp);
		tmp = strtok(NULL, ", \t\n");
		nowTile = atoi(tmp);
		return OTHER;
	}
	else if (!strcmp("tilerepeat",tmp)) {
		tmp = strtok(NULL, ", \t\n");
		if (!strcmp("YES",tmp)) 
			tileRepeat = YES;
		else
			tileRepeat = NO;
		return OTHER;
	}
	else if (!strcmp("movesTime",tmp)) {
		tmp = strtok(NULL, ", \t\n");
		movesInterval = atoi(tmp);
		tmp = strtok(NULL, ", \t\n");
		movesTimer = atoi(tmp);
		return OTHER;
	}
	else if (!strcmp("startXY",tmp)) {			// 動畫開始的座標
		tmp = strtok(NULL, "(), \t\n");
		if (!strcmp("random",tmp)) {
			tmp = strtok(NULL, "(), \t\n");
			randomNumber1 = atoi(tmp);
			tmp = strtok(NULL, "(), \t\n");
			randomNumber2 = atoi(tmp);
			startX = randomNumber1 + (arc4random() % (randomNumber2-randomNumber1+1));
		}
		else {
			startX = atoi(tmp);
		}
		tmp = strtok(NULL, ", \t\n");
		if (!strcmp("random",tmp)) {
			tmp = strtok(NULL, "(), \t\n");
			randomNumber1 = atoi(tmp);
			tmp = strtok(NULL, "(), \t\n");
			randomNumber2 = atoi(tmp);
			startY = randomNumber1 + (arc4random() % (randomNumber2-randomNumber1+1));
		}
		else {
			startY = atoi(tmp);
		}
		return OTHER;
	}
	else if (!strcmp("endXY",tmp)) {			// 動畫開始的座標
		tmp = strtok(NULL, "(), \t\n");
		if (!strcmp("random",tmp)) {
			tmp = strtok(NULL, "(), \t\n");
			randomNumber1 = atoi(tmp);
			tmp = strtok(NULL, "(), \t\n");
			randomNumber2 = atoi(tmp);
			endX = randomNumber1 + (arc4random() % (randomNumber2-randomNumber1+1));
		}
		else {
			endX = atoi(tmp);
		}
		tmp = strtok(NULL, ", \t\n");
		if (!strcmp("random",tmp)) {
			tmp = strtok(NULL, "(), \t\n");
			randomNumber1 = atoi(tmp);
			tmp = strtok(NULL, "(), \t\n");
			randomNumber2 = atoi(tmp);
			endY = randomNumber1 + (arc4random() % (randomNumber2-randomNumber1+1));
		}
		else {
			endY = atoi(tmp);
		}
		//endY = atoi(tmp);	
		return OTHER;
	}
	else if (!strcmp("extendXY",tmp)) {
		tmp = strtok(NULL, ", \t\n");
		if (!strcmp("YES",tmp)) 
			extendXY = YES;
		else
			extendXY= NO;
	}
	else if (!strcmp("movesIncXY",tmp)) {			// 動畫開始的座標
		tmp = strtok(NULL, ", \t\n");
		movesIncX = atoi(tmp);
		tmp = strtok(NULL, ", \t\n");
		movesIncY = atoi(tmp);	
		return OTHER;
	}
	else if (!strcmp("movesRepeat",tmp)) {
		tmp = strtok(NULL, ", \t\n");
		if (!strcmp("YES",tmp)) 
			movesRepeat = YES;
		else
			movesRepeat = NO;
		return OTHER;
	}
	else if (!strcmp("drawMe",tmp)) {
		tmp = strtok(NULL, ", \t\n");
		if (!strcmp("YES",tmp)) 
			drawMe = YES;
		else
			drawMe = NO;
		return OTHER;
	}
	else if (*tmp == '#') {
		return COMMENT;
	}
	return UNKNOWN;

} // parseDescription



// 將整個layer的每一個sprite，用sprite中的method計算好新的座標，再用sprite中的method去render
- (void) animate {
	NSUInteger	i, 
				count = [spriteArray count];
	
	for (i=0; i<count ;i++) {
		id tmpSprite = [spriteArray objectAtIndex:i];
		[tmpSprite animateSprite];
		if ([tmpSprite drawMe] == YES) {
			[tmpSprite drawClipAtPoint:CGPointMake((float)[tmpSprite nowX], 
												   (float)[tmpSprite nowY])];
		}
	}
	
} // animate

- (id) spriteAtIndex : (int) n {
	return [spriteArray objectAtIndex:n];
}

- (id) spriteUseKey : (char *) skey {

	LDSprite *tmpSprite;
	
	int	i;
	int cnt = [spriteArray count];
	
	for (i=0;i<cnt;i++) {
		tmpSprite = [spriteArray objectAtIndex : i];
//		if ([[tmpSprite key] caseInsensitiveCompare : skey] == NSOrderedSame) {	// same
//		if ([skey caseInsensitiveCompare : @"success.png"] == NSOrderedSame) {	// same
		if (!strcmp([tmpSprite spriteKey], skey))
			return tmpSprite;
		
	}
	return nil;
	
}

- (void) addSprite : (LDSprite *)s {
	[spriteArray addObject:s];
}

- (void) removeSpriteAtIndex : (int) n {
	
	id s;
	
	s = [spriteArray objectAtIndex : n];
//	[spriteArray removeObject : s];
	[spriteArray removeObjectAtIndex : n];
//	[s release];
	
}

- (void) removeSprite : (id) s {
	
	[spriteArray removeObject : s];
	
}

- (int) count {
	return [spriteArray count];
}

- (void) dealloc {
	[spriteArray release];
	[super dealloc];
}
@end
